import { Act } from "../../type/actType.js";
import { Item } from "prismarine-item";
import { getDamage } from "../../utils/get/getDamage.js";
import { getNearbyEntities } from "../../utils/get/getWorldData.js";
import { delayMS } from "../../utils/delay.js";
import { Bot } from "../Bot.js";
import { Entity } from "prismarine-entity";
import { formatActCallString } from "../../utils/string/formatString.js";

const _actCallString = (msg: string): string => {
  return formatActCallString(msg, attackPlayer.name);
};

async function _check(_bot: Bot, talking: boolean, targetPlayer: Entity): Promise<void> {
  const bot = _bot._bot;
  const actManager = _bot._actManager;
  const playerName = targetPlayer.username;
  actManager._state = `正在攻击玩家`;
  while (getNearbyEntities(bot, 32).includes(targetPlayer)) {
    await delayMS(500);
    if (actManager._state !== "正在攻击玩家") {
      bot.pvp.stop();
      return;
    }
    if (talking && Math.random() * 200 <= 1) {
      _bot.handleMessage(
        _actCallString(`主动消息: 你现在在和 ${playerName} 战斗，简短地说一句话！`)
      );
    }
  }
  actManager._state = "空闲";
  _bot.handleMessage(_actCallString(`结束攻击玩家 ${playerName}`));
}

export const attackPlayer: Act = {
  name: "attackPlayer",
  description: "调用后持续将攻击一个特定的玩家，直到该玩家被击败或者逃跑。",
  params: [
    {
      type: "string",
      name: "playerName",
      description: "要攻击的玩家的名字",
    },
    {
      type: "bool",
      name: "talking",
      description: "是否在攻击过程中主动说话（比如嘲讽）",
    },
  ],
  perform: async (_bot, args): Promise<string> => {
    if (_bot._actManager._state === "正在攻击玩家") return "已经在攻击玩家中，不需要重复调用";
    const bot = _bot._bot;
    const playerName = args["playerName"] as string;
    const targetPlayer = bot.players[playerName]?.entity;
    if (!targetPlayer) return `找不到玩家 ${playerName}`;
    let weapon: Item = null as any;
    for (const item of bot.inventory.items()) {
      if (!item) continue;
      if (getDamage(item.name) > 0) {
        if (!weapon) weapon = item;
        else if (getDamage(item.name) > getDamage(weapon.name)) weapon = item;
      }
    }
    if (weapon) await bot.equip(weapon, "hand");
    bot.pvp.attack(targetPlayer);
    _check(_bot, args["talking"] as boolean, targetPlayer);
    return `正在攻击的玩家 ${playerName}`;
  },
};
